<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>昌西的西昌</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f7f6;
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            position: relative;
        }

        /* 水印样式 */
        #watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 100px;
            color: rgba(200, 200, 200, 0.2);
            pointer-events: none;  /* 让水印不可点击 */
            z-index: -1;
        }

        #chat-container {
            width: 500px;
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            box-sizing: border-box;
            position: relative;
            z-index: 1;
            display: flex;
            flex-direction: column;
            height: 80vh;
        }

        /* 新增的标题容器，使用 Flexbox 对齐标题和按钮 */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        h2 {
            color: #555;
            font-weight: 300;
            margin: 0; /* 移除默认的下边距 */
        }

        /* 新增的➕号按钮样式 */
        #add-conversation-button {
            background-color: #48c78e;
            border: none;
            color: white;
            padding: 8px 12px;
            border-radius: 50%;
            font-size: 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #add-conversation-button:hover {
            background-color: #3db578;
        }

        #messages {
            flex: 1;
            border-radius: 8px;
            border: 1px solid #ddd;
            overflow-y: scroll;
            padding: 10px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
            box-shadow: inset 0px 4px 6px rgba(0, 0, 0, 0.05);
            position: relative;
        }

        /* 通用消息样式 */
        .message {
            margin: 10px 0;
            padding: 10px 15px;
            border-radius: 8px;
            box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
            max-width: 80%;
            word-wrap: break-word;
            clear: both;
            position: relative;
        }

        /* 用户消息样式 */
        .message.user {
            background-color: #d1fddc; /* 浅绿色 */
            margin-left: auto;
            text-align: right;
        }

        /* AI 消息样式 */
        .message.assistant {
            background-color: #ffffff; /* 浅蓝色 */
            margin-right: auto;
            text-align: left;
        }

        /* 加载动画在AI消息中的样式 */
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #48c78e;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-left: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #message-input {
            width: calc(100% - 150px);
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: inset 0px 2px 4px rgba(0, 0, 0, 0.05);
            outline: none;
        }

        #send-button {
            width: 80px;
            padding: 10px;
            background-color: #48c78e;
            border: none;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s ease;
        }

        #send-button:hover {
            background-color: #3db578;
        }

        .input-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
        }

        #upload-button {
            background-color: #48c78e;
            border: none;
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s ease;
        }

        #upload-button:hover {
            background-color: #3db578;
        }

        /* 图片预览样式 */
        #image-preview {
            margin-top: 10px;
            max-width: 100%;
            max-height: 150px;
            display: none; /* 初始隐藏 */
            border-radius: 8px;
            box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
        }
        #clear-button {
            width: 100%;
            padding: 10px;
            background-color: #ffc107;
            border: none;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            margin-top: 10px;
            font-weight: bold;
            transition: background-color 0.3s ease;
        }

        #clear-button:hover {
            background-color: #ffb306;
        }

        /* Scrollbar customization */
        #messages::-webkit-scrollbar {
            width: 8px;
        }

        #messages::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb {
            background: #bbb;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb:hover {
            background: #888;
        }

        /* 加载动画样式 */
        #loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none; /* 初始隐藏 */
        }

        .spinner-overlay {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #48c78e;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
        }

    </style>
</head>
<body>
    <!-- 添加水印 -->
    <div id="watermark">昌西</div>

    <!-- 加载动画 -->
    <div id="loading-overlay">
        <div class="spinner-overlay"></div>
    </div>

    <div id="chat-container">
        <!-- 新增的标题容器 -->
        <div class="header">
            <h2>西昌</h2>
            <!-- 新增的➕号按钮 -->
            <button id="add-conversation-button">+</button>
        </div>
        <div id="messages">
            <!-- 消息将动态加载 -->
        </div>
        <div class="input-group">
            <!-- 上传图片按钮 -->
            <button id="upload-button">上传</button>
            <!-- 隐藏的文件输入 -->
            <input type="file" id="image-input" accept="image/*" style="display: none;">
            <!-- 显示预览的图片 -->
            <img id="image-preview" src="#" alt="图片预览">
            <!-- 文本输入框 -->
            <input type="text" id="message-input" placeholder="输入消息...">
            <button id="send-button">发送</button>
        </div>
        <button id="clear-button">清除所有消息</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const messagesDiv = document.getElementById('messages');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const clearButton = document.getElementById('clear-button');
            const addConversationButton = document.getElementById('add-conversation-button');
            const loadingOverlay = document.getElementById('loading-overlay');
            const uploadButton = document.getElementById('upload-button');
            const imageInput = document.getElementById('image-input');
            const imagePreview = document.getElementById('image-preview');

            let img_name = '';
            let img_url = '';
            let awaiting_ai_reply = false;  // 标记是否在等待AI回复
            let last_message_id = 0;  // 记录最后一条消息的ID

            // 显示加载动画
            function showLoading() {
                loadingOverlay.style.display = 'flex';
            }

            // 隐藏加载动画
            function hideLoading() {
                loadingOverlay.style.display = 'none';
            }

            // 禁用输入和按钮
            function disableInputs() {
                messageInput.disabled = true;
                sendButton.disabled = true;
                addConversationButton.disabled = true;
                clearButton.disabled = true;
                uploadButton.disabled = true;
                imageInput.disabled = true;
            }

            // 启用输入和按钮
            function enableInputs() {
                messageInput.disabled = false;
                sendButton.disabled = false;
                addConversationButton.disabled = false;
                clearButton.disabled = false;
                uploadButton.disabled = false;
                imageInput.disabled = false;
            }

            // 加载现有消息
            function loadMessages() {
                fetch('/get_messages')
                    .then(response => response.json())
                    .then(data => {
                        const existingMessages = Array.from(messagesDiv.children).map(msg => msg.getAttribute('data-id'));
                        const newMessages = data.messages;

                        // 清空消息显示区域
                        messagesDiv.innerHTML = '';

                        newMessages.forEach(msg => {
                            const msgDiv = document.createElement('div');
                            msgDiv.classList.add('message');

                            if (msg.role === 'user') {
                                msgDiv.classList.add('user');
                            } else if (msg.role === 'assistant') {
                                msgDiv.classList.add('assistant');
                            }

                            // 设置数据ID属性，方便追踪
                            msgDiv.setAttribute('data-id', msg.id);

                            const msgText = document.createElement('span');
                            msgText.classList.add('message-text');
                            msgText.textContent = msg.text;

                            msgDiv.appendChild(msgText);

                            // 如果消息包含 file_ids，显示图片
                            if (msg.file_ids && msg.file_ids.length > 0) {
                                msg.file_ids.forEach(file_id => {
                                    const imgElement = document.createElement('img');
                                    imgElement.src = `https://your-image-host.com/${file_id}`; // 请根据实际情况修改
                                    imgElement.alt = '上传的图片';
                                    imgElement.style.maxWidth = '100px';
                                    imgElement.style.maxHeight = '100px';
                                    imgElement.style.display = 'block';
                                    imgElement.style.marginTop = '10px';
                                    msgDiv.appendChild(imgElement);
                                });
                            }

                            messagesDiv.appendChild(msgDiv);

                            // 更新 last_message_id
                            if (msg.id > last_message_id) {
                                last_message_id = msg.id;
                            }
                        });

                        // 如果在等待AI回复，并且AI回复已到达，移除临时消息
                        if (awaiting_ai_reply) {
                            // 找到最新的AI消息
                            const latest_ai_message = newMessages.slice().reverse().find(msg => msg.role === 'assistant');
                            if (latest_ai_message && latest_ai_message.id > last_message_id - 1) {
                                // AI回复已经到达，移除临时AI消息
                                const tempAiMessage = document.querySelector('.message.assistant.temp');
                                if (tempAiMessage) {
                                    messagesDiv.removeChild(tempAiMessage);
                                }
                                awaiting_ai_reply = false;
                            }
                        }

                        messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    })
                    .catch(error => {
                        console.error('加载消息时出错:', error);
                    });
            }

            // 发送消息
            sendButton.addEventListener('click', () => {
                const message = messageInput.value.trim();
                if (message !== '' || img_name !== '') {
                    showLoading();
                    disableInputs();

                    const payload = {
                        'message': message,
                        'img_name': img_name,
                        'img_url': img_url,
                        'max_length': 500
                    };

                    fetch('/send_message', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(payload)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            // 仅清空输入框和图片信息
                            messageInput.value = '';
                            img_name = '';
                            img_url = '';
                            imagePreview.src = '#';
                            imagePreview.style.display = 'none';

                            // 添加临时AI消息框
                            const tempAiDiv = document.createElement('div');
                            tempAiDiv.classList.add('message', 'assistant', 'temp');
                            tempAiDiv.setAttribute('data-id', 'temp-ai');
                            const tempAiText = document.createElement('span');
                            tempAiText.classList.add('message-text');
                            tempAiText.textContent = 'AI正在回复';
                            const spinner = document.createElement('span');
                            spinner.classList.add('spinner');
                            tempAiDiv.appendChild(tempAiText);
                            tempAiDiv.appendChild(spinner);
                            messagesDiv.appendChild(tempAiDiv);
                            messagesDiv.scrollTop = messagesDiv.scrollHeight;

                            awaiting_ai_reply = true;
                        } else {
                            alert('发送失败: ' + data.message);
                        }
                        hideLoading();
                        enableInputs();
                        loadMessages(); // 重新加载消息
                    })
                    .catch(error => {
                        console.error('发送消息时出错:', error);
                        hideLoading();
                        enableInputs();
                    });
                }
            });

            // 允许按 Enter 键发送消息
            messageInput.addEventListener('keyup', (event) => {
                if (event.key === 'Enter') {
                    sendButton.click();
                }
            });

            // 上传图片按钮点击事件
            uploadButton.addEventListener('click', () => {
                imageInput.click();
            });

            // 处理图片选择
            imageInput.addEventListener('change', () => {
                const file = imageInput.files[0];
                if (file) {
                    // 显示预览
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        imagePreview.src = e.target.result;
                        imagePreview.style.display = 'block';
                    }
                    reader.readAsDataURL(file);

                    // 上传图片到后端
                    showLoading();
                    disableInputs();

                    const formData = new FormData();
                    formData.append('image', file);

                    fetch('/upload_image', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            img_name = data.img_name;
                            img_url = data.img_url;
                            alert('图片上传成功');
                        } else {
                            alert('图片上传失败: ' + data.message);
                            img_name = '';
                            img_url = '';
                            imagePreview.src = '#';
                            imagePreview.style.display = 'none';
                        }
                        hideLoading();
                        enableInputs();
                        // 清除文件输入
                        imageInput.value = '';
                    })
                    .catch(error => {
                        console.error('上传图片时出错:', error);
                        hideLoading();
                        enableInputs();
                        alert('图片上传出错');
                        img_name = '';
                        img_url = '';
                        imagePreview.src = '#';
                        imagePreview.style.display = 'none';
                    });
                }
            });

            // 清除所有消息并创建新对话
            clearButton.addEventListener('click', () => {
                if (confirm('确定要清除所有消息吗？')) {
                    showLoading();
                    disableInputs();
                    fetch('/clear_messages', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            loadMessages(); // 重新加载消息
                            alert('已创建新的对话');
                        } else {
                            alert('清除失败: ' + data.message);
                        }
                        hideLoading();
                        enableInputs();
                    })
                    .catch(error => {
                        console.error('清除消息时出错:', error);
                        hideLoading();
                        enableInputs();
                    });
                }
            });

            // 新增的➕号按钮点击事件，创建新的对话
            addConversationButton.addEventListener('click', () => {
                showLoading();
                disableInputs();
                fetch('/create_conversation', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        loadMessages(); // 重新加载消息
                        alert('已创建新的对话');
                    } else {
                        alert('创建对话失败: ' + data.message);
                    }
                    hideLoading();
                    enableInputs();
                })
                .catch(error => {
                    console.error('创建对话时出错:', error);
                    hideLoading();
                    enableInputs();
                });
            });

            // 定时刷新消息，每2秒调用一次 loadMessages()
            setInterval(loadMessages, 2000);

            // 初始加载消息
            loadMessages();
        });
    </script>
</body>
</html>